"""
des: 
author: 邵宁
date: 2022-09-15
"""

import time
import ctypes
import inspect
import requests
import threading
from contextlib import closing


def stop_thread(thread):
    def _async_raise(tid, exc_type):
        tid = ctypes.c_long(tid)
        if not inspect.isclass(exc_type):
            exc_type = type(exc_type)
        res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exc_type))
        if res == 0:
            raise ValueError("invalid thread id")
        elif res != 1:
            ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
            raise SystemError("PyThreadState_SetAsyncExc failed")

    _async_raise(thread.ident, SystemExit)


class SessionTemplate:
    def __init__(self, *args):
        self.session_id = "t_" + time.strftime("%Y%m%d_%H%M%S")
        self.session_name = ""
        self.session_obj = threading.Thread(target=self.work, args=args)
        self.session_percent = 0
        self.session_status = "waiting"  # [waiting\running\stop]

    def start(self):
        self.session_status = "running"
        self.session_obj.start()

    def stop(self):
        stop_thread(self.session_obj)
        self.session_status = "stop"

    def status(self):
        pass

    def restart(self):
        pass

    def work(self, *args):
        raise NotImplemented


class SessionDownload(SessionTemplate):
    def work(self, download_url):
        try:
            with closing(requests.get(download_url, stream=True)) as response:
                chunk_size = 1024  # 单次请求最大值
                content_size = int(response.headers['content-length'])  # 内容体总大小
                data_count = 0
                data_list = []
                for data in response.iter_content(chunk_size=chunk_size):
                    data_list.append(data)
                    data_count = data_count + len(data)
                    now_jd = (data_count / content_size) * 100
                    self.session_percent = int(now_jd)
                # pdf_upload(data_list, username=username, paper_url=paper_url) 下载完成回调函数
        except Exception as e:
            pass
        self.session_status = "stop"


class SessionManage:
    def __init__(self):
        self.session_self = None
        self.session_list = []  # 保存所有会话
        self.thread_list_running = []  # 线程池
        self.thread_list_waiting = []

    def session_manage_thread(self):
        while True:
            for thread_one in self.thread_list_running:
                if thread_one.session_status == "stop":
                    self.thread_list_running.remove(thread_one)

    def get_session_by_session_token(self):
        pass

    def join(self, session_one):
        pass

    def session_status_list(self):
        pass

    def session_start_one(self):
        pass

    def session_restart_one(self):
        pass

    def session_stop_one(self):
        pass

    def session_status_one(self):
        pass

    def session_delete_one(self):
        pass


if __name__ == '__main__':
    s = SessionDownload("http://10.1.123.157/ns86/BaseOS/Packages/ModemManager-1.18.2-1.el8.src.rpm")
    s.start()
    time.sleep(1)
    print(s.session_percent)
